package com.tf8.treasure.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tf8.treasure.entity.Session;
import com.tf8.treasure.service.SessionService;
import com.tfg.mid.redis.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Collection;

@Service
public class SessionServiceImpl implements SessionService {
    private final static String sessionKey="love:treasure:session::";

    @Autowired
    private RedisClient redisClient;

    private int seconds = 3600;

    @Override
    public Session create(String sessionId, Session session) {
        redisClient.setEx(getRedisSessionKey(sessionId),seconds, JSON.toJSONString(session));
        return session;
    }

    @Override
    public Session readSession(Serializable sessionId) {
        /*Session s=new Session();
        //s.setUserId("2088102178136658");
        s.setUserId("2088602339180273");
        return s;*/
        String s = redisClient.get(getRedisSessionKey(sessionId));
        if(StringUtils.isEmpty(s)) return null;
        return JSON.parseObject(s,new TypeReference<Session>(){});
    }

    @Override
    public void update(String sessionId,Session session) {
        redisClient.setEx(getRedisSessionKey(sessionId),seconds, JSON.toJSONString(session));
    }

    @Override
    public void delete(String sessionId) {}

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }

    /**
     * 获取redis中的session key
     *
     * @param sessionId
     * @return
     */
    private String getRedisSessionKey(Serializable sessionId) {
        return this.sessionKey + sessionId;
    }
}
